﻿#include "AntiAliasingAttachments.h"
#include "Render/VulkanContext.h"
#include "Render/Texture/GPURenderTarget.h"

CAntiAliasingAttachments::CAntiAliasingAttachments(vk::Extent2D InViewportSize)
{
    ViewportSize=InViewportSize;

    AntialiasingOutput= std::make_shared<CGPURenderTarget>();
    AntialiasingOutput->Initialize(vk::Extent3D(InViewportSize.width, InViewportSize.height, 1), 
        vk::Format::eR16G16B16A16Sfloat,
        vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc
    );

    //create framebuffer
    std::vector<vk::ImageView> Attachments = {
        AntialiasingOutput->GetImageView(),
    };

    vk::FramebufferCreateInfo FrameBufferInfo = vk::FramebufferCreateInfo()
        .setRenderPass(CVulkanContext::Get()->GetSceneGlobal()->AntiAliasingRenderPass)
        .setAttachmentCount(Attachments.size())
        .setPAttachments(Attachments.data())
        .setWidth(InViewportSize.width)
        .setHeight(InViewportSize.height)
        .setLayers(1);

    FrameBuffer = CVulkanContext::Get()->GetDevice().createFramebuffer(FrameBufferInfo);

    ClearValues={
        vk::ClearColorValue(std::array<float, 4>{0.0f, 0.0f, 0.0f, 1.0f})
    };
}

CAntiAliasingAttachments::~CAntiAliasingAttachments()
{
    CVulkanContext::Get()->GetDevice().destroyFramebuffer(FrameBuffer);
}

void CAntiAliasingAttachments::PrepareSelfRecord()
{
    SVulkanDescriptorPoolSize PoolSize;
    PoolSize.SetNum=1;
    PoolSize.DescriptorNums.CombinedImageSamplerDescriptorNum=1;
    CVulkanContext::Get()->GetAutoResetDescriptorPool()->GenerallPool.PoolSize+=PoolSize;

}

void CAntiAliasingAttachments::CreateDescriptorSet(std::shared_ptr<CGPURenderTarget> InFormerColor)
{

    vk::DescriptorSetAllocateInfo AllocInfo = vk::DescriptorSetAllocateInfo()
        .setDescriptorPool(CVulkanContext::Get()->GetAutoResetDescriptorPool()->GenerallPool.Pool)
        .setDescriptorSetCount(1)
        .setPSetLayouts(
            &CVulkanContext::Get()->GetSceneGlobal()->AntiAliasingDescriptorSetLayout.Layout
        );

    DescriptorSet = CVulkanContext::Get()->GetDevice().allocateDescriptorSets(AllocInfo)[0];

    vk::DescriptorImageInfo ImageInfo = vk::DescriptorImageInfo()
        .setSampler(CVulkanContext::Get()->GetDefaultImageSampler())
        .setImageView(InFormerColor->GetImageView())
        .setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);

    vk::WriteDescriptorSet Write = vk::WriteDescriptorSet()
        .setDstSet(DescriptorSet)
        .setDstBinding(0)
        .setDstArrayElement(0)
        .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
        .setDescriptorCount(1)
        .setPImageInfo(&ImageInfo);

    CVulkanContext::Get()->GetDevice().updateDescriptorSets(Write, nullptr);


}
